﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Common;
using System.Text.RegularExpressions;
using System.Configuration;
using DataBaseHelper;
using System.Data;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using System.Text;

/// <summary>
/// SignIn 处理用户登录和注册
/// </summary>
public static class SignIn
{
    public class Result
    {
        public bool bOk = false;
        public string sMsg = null;
        public string sDebug = null;
        public string sActions = null;
        public object data = null;
    }

    private static JavaScriptSerializer JSON = new JavaScriptSerializer();
    private static string constring = ConfigurationManager.ConnectionStrings["FLOW"].ToString();
    private static Regex signin = new Regex("^[0-9a-zA-Z]{6}$");
    private static string signinSql = 
@"SELECT TOP 1 *
FROM [V_PlayerInfo]
WHERE
[EPass] = @epass";

    public static string DoSignIn(HttpRequest request, HttpSessionState Session)
    {
        Result res = new Result();
        string pass = string.IsNullOrWhiteSpace(request["epass"]) ? "" : request["epass"].ToUpper();
        if (signin.IsMatch(pass))
        {
            try
            {
                IDBS dbs = new SqlDBS();
                DbParameter[] dbp = { dbs.CreateParameter() };
                dbp[0].DbType = DbType.String;
                dbp[0].ParameterName = "epass";
                dbs.Prepare(signinSql, dbp);
                dbs.SetParam(0, pass);
                DataSet ds;
                if (dbs.ExecuteQuery(out ds))
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        Session["EPASS"] = pass;
                        Session["USER"] = new User(ds.Tables[0].Rows[0]);
                        res.bOk = true;
                        res.sMsg = "登录成功";
                        res.sActions = "/Signed";
                    }
                    else
                    {
                        res.bOk = false;
                        res.sMsg = "登录失败，无效的通行证号";
                    }
                }
                else
                {
                    res.bOk = false;
                    res.sMsg = "登录失败，无效的通行证号";
                }
            }
            catch (Exception ex)
            {
                res.bOk = false;
                res.sMsg = "服务器内部错误";
                res.sDebug = ex.Message;
            }
        }
        else
        {
            res.bOk = false;
            res.sMsg = "登录失败，无效的通行证号";
        }

        return JSON.Serialize(res);
    }

    private static string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static string GenPass(string username)
    {
        StringBuilder sb = new StringBuilder();
        Random rnd = new Random((int)(username.GetHashCode() + DateTime.Now.Ticks));
        while (sb.Length < 6)
        {
            sb.Append(chars[rnd.Next(0, chars.Length - 1)]);
        }
        return sb.ToString();
    }

    private static string signupSQL =
@"
INSERT INTO [M_Player] SELECT
	@EPASS,
	@NAME,
	GETDATE()
WHERE
	NOT EXISTS (
		SELECT
			*
		FROM
			[M_Player]
		WHERE
			[Nickname] = @NAME
		OR [Identification] = @EPASS
	)
";

    public static string DoSignUp(HttpRequest request, HttpSessionState Session)
    {
        var res = new Result();
        string Name = string.IsNullOrWhiteSpace(request["user"]) ? "" : request["user"];
        if (!Name.Equals(""))
        {
            try
            {
                string EPASS = GenPass(Name);
                IDBS dbs = new SqlDBS();
                DbParameter[] dbp = { dbs.CreateParameter(), dbs.CreateParameter() };
                dbp[0].ParameterName = "EPASS";
                dbp[0].DbType = DbType.String;
                dbp[1].ParameterName = "NAME";
                dbp[1].DbType = DbType.String;
                dbs.Prepare(signupSQL, dbp);
                dbs.SetParam("EPASS", EPASS);
                dbs.SetParam("NAME", Name);
                int r = dbs.ExecuteNonQuery();
                if (r == 1)
                {
                    res.bOk = true;
                    res.sMsg = "注册成功。";
                    res.data = new { EPASS = EPASS };
                }
                else if (r == 0)
                {
                    res.bOk = false;
                    res.sMsg = "注册失败。昵称已被使用";
                    res.sDebug = "No Changes.";
                    res.data = new { FEPASS = EPASS, NAME = Name };
                }
                else
                {
                    res.bOk = false;
                    res.sMsg = "注册失败。服务器内部错误。";
                    Exception ex = dbs.LastError;
                    res.sDebug = ex.Message;
                }
            }
            catch (Exception ex)
            {
                res.bOk = false;
                res.sMsg = "注册失败。服务器内部错误。";
                res.sDebug = ex.Message;
            }
        }
        else
        {
            res.bOk = false;
            res.sMsg = "注册失败，无效的昵称";
        }
        return JSON.Serialize(res);
    }
}

[Serializable]
public class User
{
    public int ID { get; private set; }
    public string EPASS { get; private set; }
    public string NAME { get; private set; }
    public DateTime REGTIME { get; private set; }
    public decimal POINT { get; set; }
    public int LEVEL
    {
        get
        {
            if (POINT < 1000)
            {
                return 1;
            }
            else if (POINT < 2700)
            {
                return 2;
            }
            else if (POINT < 4750)
            {
                return 3;
            }
            return 0;
        }
    }

    public User()
    {
        ID = 0;
        EPASS = "000000";
        NAME = "Guest";
        REGTIME = DateTime.MinValue;
        POINT = 0;
    }

    public User(DataRow dr)
    {
        ID = dr["ID"] as int? ?? -1;
        EPASS = dr["EPass"] as string;
        NAME = dr["Name"] as string;
        REGTIME = dr["Regtime"] as DateTime? ?? DateTime.Now;
        POINT = dr["TotalPoints"] as decimal? ?? 0;
    }
}